package cn.aj.org.service.impl;

import cn.aj.aop.LogAop;
import cn.aj.basic.service.impl.BaseServiceImpl;
import cn.aj.org.domain.Department;
import cn.aj.org.mapper.DepartmentMapper;
import cn.aj.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper mapper;

    @Override
    @LogAop(name = "部门新增方法")
    public void add(Department department) {
        super.add(department);
    }

    @Override
    @LogAop(name = "部门修改方法")
    public void update(Department department) {
        super.update(department);
    }

    /**
    * @Description: TODO
    * @Author: aj
    * @Version: 1.0
    * @Date:  2022/11/12 0012 10:35
     * 批量删除
    */
    @Override
    @Transactional
    @LogAop(name = "部门批量删除")
    public void batchDelete(List<Long> ids) {
        mapper.batchDelete(ids);
    }

    /**
    * @Description: TODO
    * @Author: aj
    * @Version: 1.0
    * @Date:  2022/11/13 0013 22:14
     * 无限极树
    */
    @Override
    @LogAop(name = "部门无限极树")
    public List<Department> loadTree() {
        List<Department> departmentList = mapper.loadTree(); // 无限极树返回一个list集合
        // list转map
        // Map<Long, Department> map = departmentList.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        ArrayList<Department> arrayList = new ArrayList<Department>();
        // 先找最大的爹
        for (Department parent : departmentList) {
            if (parent.getParentId() == null) {
                arrayList.add(parent); // 找到最大的爹
            } else{
                // 儿子找爹
                for (Department children : departmentList) {
                    if (children.getId().equals(parent.getParentId())) {
                        children.getChildren().add(parent);
                        break;
                    }
                }
            }
        }
        return arrayList;
    }
}
